'''
Created on 2011-3-13

@author: Frank F Zhang
'''
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import login, authenticate
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.db import transaction
from django.contrib.auth.models import User

from aboutfamily.user.forms import UserLoginForm, UserSignupForm
from aboutfamily.user.models import Profile

def user_login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse("blog_index"))
    
    if request.method == "POST":
        loginform = UserLoginForm(request.POST)
        if loginform.is_valid():
            user = loginform.user
            if user is not None:
                login(request, user)
            return HttpResponseRedirect(reverse("blog_index"))
    else:
        loginform = UserLoginForm()
    
    return render_to_response("user_login.html.template", {
        "loginform": loginform           
    }, context_instance=RequestContext(request))
    
    
@transaction.commit_on_success
def user_signup(request):
    #login user cannot signup again
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse("blog_index"))
    
    if request.method == "POST":
        signupform = UserSignupForm(request.POST)
        if signupform.is_valid():
            data = signupform.cleaned_data
            new_user = User.objects.create_user(username=data["email"],
                                                email=data["email"],
                                                password=data["password1"])
            profile = Profile.get_new_profile(new_user)
            profile.first_name = new_user.first_name
            profile.last_name = new_user.last_name
            profile.save()
            new_user = authenticate(username=data["email"], password=data["password1"])
            login(request, new_user)
        return render_to_response("user_signup_success.html.template",{},context_instance=RequestContext(request))
        #return HttpResponseRedirect(reverse("user_edit_profile"))
    else:
        signupform = UserSignupForm()
        return render_to_response("user_signup.html.template", {
	        "selected": 2,
	        "signupform": signupform       
	    }, context_instance=RequestContext(request))
